package com.bzgwl.authentication.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bzgwl.authentication.mapper.PermissionMapper;
import com.bzgwl.authentication.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Professor_Kong
 * @version 1.0
 * @date 2020/2/28 11:18
 */
@Service
public class
MyUserDetailService implements UserDetailsService {


    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",s);
        List<com.bzgwl.authentication.entity.User> list = userMapper.selectList(queryWrapper);


        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        List<String> roles = permissionMapper.findUserPermissionByName(s);


        if(roles!=null && roles.size()>0){
            for(String role : roles){
                GrantedAuthority grantedAuthority2 = new SimpleGrantedAuthority(role);
                authorities.add(grantedAuthority2);
            }
        }

        if(list!=null && list.size()> 0){
            com.bzgwl.authentication.entity.User user = list.get(0);

            User user1 = new User(
                    user.getUsername(),
                    user.getPassword(),
                    authorities);
            return user1;
        }
        return null;
    }
}
